﻿function VotingSitesCrawler(campaignRootUrl) {
	var regexRegion = /region\=([0-9]+)/;

	function scrapePage(url, receiver, onCompletion) {
		var acceptor = function (page) {
			var votingSites = [];

			$('form[name=go_reg] > select[name=gs] > option', $(page)).not(':contains(---)').each(function (index, e) {
				votingSites.push({ name: $(e).text(), href: $(e).val() });
			});
			receiver(votingSites);
		};

		$.ajax({
			url: url,
			cache: false,
			dataType: 'html',
			success: acceptor,
			complete: onCompletion
		});
	}

	function fixRegions(nodes, region) {
		$.each(nodes, function (i, node) {
			if (node.region != undefined)
				region = node.region;
			if (node.subordinates != undefined)
				fixRegions(node.subordinates, region);
			else
				node.href = node.href.replace("type=0", "type=227");
			node.href = node.href.replace("region=0", "region=" + region);
			node.href = node.href.replace("sub_region=0", "sub_region=" + region);
		});
	}

	this.run = function (onCompletion) {
		var _hierarchy = [];
		var _incomplete = 1;

		function processCompletion() {
			if (0 == --_incomplete) {
				fixRegions(_hierarchy);
				onCompletion(_hierarchy);
			}
		}

		scrapePage(campaignRootUrl, function (sites) {
			_incomplete += sites.length;
			$.each(sites, function (i, site) {
				_hierarchy.push(site);
				scrapePage(site.href, function (sites) {

					if (sites.length > 0) {
						++_incomplete;
						$.ajax({
							url: sites[0].href,
							cache: false,
							dataType: 'html',
							success: function (page) {
								var href = $("a:contains('сайт избирательной комиссии субъекта Российской Федерации')", page).attr('href');
								var match = regexRegion.exec(href);

								site.region = match != null ? 1 * match[1] : 0;
							},
							complete: processCompletion
						});
					}

					site.subordinates = sites;
				}, processCompletion);
			});
		}, processCompletion);
	};
}
